/**
 * Created by ruiyuan on 15-9-21.
 */

var Community = mongoose.model('community');
var Goods = mongoose.model('goods');
var Users = mongoose.model('user');
var geolib = require('geolib');
var goodsReply = mongoose.model('goods_reply');
var async = require('async');
var moment = require('moment');
var GoodsQueryTerms = mongoose.model('goods_queryTerms');
var GoodsCategory = mongoose.model('goods_category');
var Banner = mongoose.model('banner');
var UserFollowups = mongoose.model('user_followups');
var toolUtil = require('../common/utils/toolUtil');
var ActivityCommunity = mongoose.model('activity_community');
var ActivityPartake = mongoose.model('activity_community_partake_info');
var GoodsSaleRecord = mongoose.model('goods_sale_userRecord');
var Solr = require('solr-client');
var questionService = require('./questionService');
/*  宝宝树66小区二次改造    add   chenf  20170714   start   */
var taskService = require('./taskService');
/*  宝宝树66小区二次改造    add   chenf  20170714   end   */

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170816   start   */
var communityService = require('../services/communityService');
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170816   end   */

/*  宝宝树66小区三次改造    add   guo.xiaomin  20170928   start   */
var userService = require('../services/userService');
/*  宝宝树66小区三次改造    add   guo.xiaomin  20170928   end   */

/**
 * 集市banner
 * @param user
 * @param callback
 */
exports.getMarketBannersService = function (user, callback) {
    Banner.find({
        beginDate: {$lte: new Date()},
        endDate: {$gte: new Date()},
        type: 2,
        isValid: true,
        "$or": [
            {city: user.community.cityId},
            {level: 0}]
    }, 'url imageURL name bannerOrder').sort({bannerOrder: -1}).exec(function (err, result) {
        if (err) {
            callback(err)
        } else {
            result.forEach(function (temp) {
                temp.imageURL = imgHost + temp.imageURL + '?imageView2/1/h/276/w/750/q/75/format/jpg'
            });
            callback(null, result)
        }
    })
};

/**
 * 商品热门
 * @param callback
 */
exports.getGoodsHotQueryTermsService = function (callback) {
    GoodsCategory.find({isHot: true}, 'name img', function (err, result) {
        result.forEach(function (temp) {
            temp._doc.type = 2;
            temp._doc.value = temp._id + '';
        });
        callback(err, result);
    }).sort('-displayOrder')
};

/**
 * 商品分类列表
 * @param callback
 */
exports.getGoodsCategoryListService = function (itemType, callback) {
    GoodsCategory.find({itemType: itemType}, 'name img').sort('-displayOrder').exec(callback)
};

/* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 start */
// 1120-commit-master
/**
 * 闲置商品分类列表
 * @param callback
 */
exports.searchGoodsCategoryListService = function (itemType, callback) {
    GoodsCategory.find({itemType: itemType}, 'name _id').sort('-displayOrder').exec(callback)
};
/* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 end */

/**
 * 新增二手商品
 * @param user
 * @param input
 * @param callback
 */
exports.addNewGoodsService = function (user, input, callback) {

    ActivityCommunity.findOne({
        type: 1,
        isValid: true,
        beginDate: {$lt: new Date()},
        endDate: {$gt: new Date()}
    }, function (err, activity) {
        if (activity != null) {
            ActivityPartake.findOne({user: user._id, activity: activity._id}, function (err, partake) {
                if (partake != null)
                    input.saleNumber = partake.saleNumber;
                exports.addNewGoodsN(user, input, callback)
            })
        } else {
            exports.addNewGoodsN(user, input, callback);
        }
    });

};

exports.addNewGoodsN = function (user, input, callback) {

    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170816   start   */
    var currUserId = user._id;
    var currCommunityId = "";
    var currCityId = "";
    var currLocation = null;
    async.series([
        function(callbackInner) {
            redisClient.get(currUserId + ":currCommunityId", function (errComm, replyComm) {
                if (!errComm) currCommunityId = replyComm;
                callbackInner(null, replyComm);
                logger.debug("currCommunityId..." + currCommunityId);
            });
        },
        function(callbackInner) {
            redisClient.get(currUserId + ":currCityId", function (errCity, replyCity) {
                if (!errCity) currCityId = replyCity;
                callbackInner(null, replyCity);
                logger.debug("currCityId..." + currCityId);
            });
        },
        function(callbackInner) {
            communityService.searchCommunityInfoByCommunityIdService(currCommunityId, function (err, data) {
                if (data && data._doc) {
                    currLocation = data._doc.location;
                }
                callbackInner(null, data._doc.location); // 回调写在这里?
                    logger.debug("currLocation 0011..." + currLocation.longitude);
                    logger.debug("currLocation 0012..." + data._doc.location.longitude);
                    logger.debug("currLocation 0021..." + currLocation.latitude);
                    logger.debug("currLocation 0022..." + data._doc.location.latitude);
            });
        }
    ], function(err1, result1) {
        logger.debug("currCommunityId+CityId+CurrLocation...OK");
        currCommunityId = result1[0];
        currCityId = result1[1];
        currLocation = result1[2];
        if(currCommunityId == null || currCommunityId == '') {
            currCommunityId = user.community._id;
        }
        if(currCityId == null || currCityId == '') {
            currCityId = user.community.cityId;
        }
        if(currLocation == null || currLocation == []) {
            currLocation = user.community.location;
        }
        // TODO 测试是否是查询小区后经纬度问题-start
        currLocation = user.community.location;
        // TODO 测试是否是查询小区后经纬度问题-end

        questionService.getAroundCommunityList(user, function (value) {
            var goods = new Goods(input);
            // goods.community = user.community._id; // 旧
            goods.community = currCommunityId; // 新
            goods.aroundCommunity = value;
            // goods.city = user.community.cityId; // 旧
            goods.city = currCityId; // 新
            goods.communityPrice = user.community.price;
            goods.communityDateBuild = user.community.dateBuild;
            // goods.location = user.community.location; // 旧
            goods.location = currLocation; // 新
            goods.createdBy = user._id;
            var itemType = 1;  // default: 闲置
            if (parseInt(input.itemType) > 0) {
                itemType = parseInt(input.itemType);
            }
            goods.itemType = itemType;
            goods.priceOrder = Number((input.presentPrice ? input.presentPrice + '' : '0' ) + Math.round(new Date() / 1000));
            goods.locOrder = {
                // longitude: user.community.location.longitude.toFixed(4) + '' + (4000000000 - Math.round(new Date().getTime() / 1000)), // 旧
                // latitude: user.community.location.latitude // 旧
                longitude: currLocation.longitude.toFixed(4) + '' + (4000000000 - Math.round(new Date().getTime() / 1000)), // 新
                latitude: currLocation.latitude // 新
            };
            // goods.point = user.community.location.latitude + ',' + user.community.location.longitude; // 旧
            goods.point = currLocation.latitude + ',' + currLocation.longitude; // 新
            if (user.community.communityType == 0) {
                goods.fromFlag = 'operate'
            }

            logger.debug("before goods.save...OK");
            goods.save(function (err, result) {
                if(err) {
                    logger.debug("goods.save.err:::" + err);
                    callback(err, result);
                } else {
                    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170919   start   */
                    userService.pushMessageToFollowers(user._id, 'secondhand', null);
                    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170919   end   */
                    // logger.debug("goods.save.result:::" + result);
                    // try{
                    //     logger.debug("JSON.parse(result):::" + JSON.parse(result));
                    // }
                    // catch(_error) {
                    //     logger.debug("JSON.parse(result)@error");
                    // }
                    // redisClient.EXISTS('goods:smart:community:' + user.community._id, function (err, flag) { // 旧
                    redisClient.EXISTS('goods:smart:community:' + currCommunityId, function (err, flag) { // 新
                        logger.debug("flag:::" + currCommunityId + "@" + flag);
                        // TODO，不保存数据库
                        // if (flag == 1) { // 旧
                        if (flag >= 0) { // 新(暂时修改方案，不知道flag有何用)
                            // redisClient.ZREVRANK('sim_communities:' + user.community._id, user.community._id, function (err, i) { // 旧
                            // redisClient.zadd('goods:smart:community:' + user.community._id, (i ? Number(i) : 0) + Number('0.' + new Date().getTime()), result._id + ',' + input.category); // 旧
                            redisClient.ZREVRANK('sim_communities:' + currCommunityId, currCommunityId, function (err, i) { // 新
                                if(result != null) { // 只有不为空时，才执行
                                    redisClient.zadd('goods:smart:community:' + currCommunityId, (i ? Number(i) : 0) + Number('0.' + new Date().getTime()), result._id + ',' + input.category); // 新
                                }
                                callback(err, result);
                                logger.debug("goods.save 01...OK");
                            });
                        } else {
                            callback(err, result);
                            logger.debug("goods.save 02...OK");
                        }
                    });
                }
            });
        });
    });
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170816   end   */
};

/**
 * 获取收藏的二手列表
 * @param user
 * @param ts
 * @param callback
 */
exports.getFollowGoodsListService = function (user, ts, callback) {
    var index = Number(ts) * listPageSize;

    UserFollowups.find({user: user._id, category: 'goods'}, 'goods dateCreated')
        .skip(index).limit(listPageSize).sort('-dateCreated')
        .exec(function (err, result) {
            async.each(result, function (follow, callbackInner) {
                Goods.findOne({_id: follow.goods}, 'itemType images title presentPrice originalPrice dealStatus type createdBy dateCreated')
                    .populate('createdBy', 'nickName images')
                    .exec(function (err, goods) {
                        follow._doc.goods = goods;
                        follow._doc.detailUrl = "http://" + restHostIp + "/market/detail.html?goodsId=" + goods._id;

                        callbackInner();
                    })
            }, function (err) {
                var data = {
                    ts: Number(ts) + 1,
                    list: result
                };
                callback(err, data);
            })
        })
};

/**
 * 商品列表
 * @param user
 * @param query
 * @param ts
 * @param callback
 */
exports.getGoodsListService = function (user, ts, query, callback) {


    var dealDate = moment().add(-7, 'day').toDate();

    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
    // redis保存取得用户选择小区ID,城市ID
    var currUserId = user._id; // 用户ID
    var communityId = ''; // 小区ID
    var cityId = ''; // 城市ID

    async.parallel([
        function(callbackInner) {
            redisClient.get(currUserId + ":currCommunityId", function (errComm, replyComm) {
                if (!errComm) communityId = replyComm;
                callbackInner(null, replyComm);
            });
        },
        function(callbackInner) {
            redisClient.get(currUserId + ":currCityId", function (errCity, replyCity) {
                if (!errCity) cityId = replyCity;
                callbackInner(null, replyCity);
            });
        }
    ], function(err, result) {

        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   start   */
        // 旧版本对应
        logger.debug(result);
        communityId = result[0];
        cityId = result[1];
        if(communityId == undefined || communityId == null || communityId == '') {
            communityId = user.community._id;
        }
        if(cityId == undefined || cityId == null || cityId == '') {
            cityId = user.community.cityId;
        }
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   end   */

        // var communityId = user.community._id; // 旧
        // var cityId = user.community.cityId; // 旧

        var currLocation = user.community.location;
        communityService.searchCommunityInfoByCommunityIdService(communityId, function (err, communityData) {
            if (communityData && communityData._doc) {
                currLocation = communityData._doc.location;
            }

            // var lat = query.lat ? Number(query.lat) : user.community.location.latitude; // 旧
            // var lng = query.lng ? Number(query.lng) : user.community.location.longitude; // 旧
            var lat = query.lat ? Number(query.lat) : currLocation.latitude; // 新
            var lng = query.lng ? Number(query.lng) : currLocation.longitude; // 新

            //查询条件
            var opt = {
                isValid: true,
                isInit: 1,
                'images.0': {$exists: true}
            };

            if (query.type && parseInt(query.type) > 0)
                opt.type = parseInt(query.type);
            if (query.itemType && parseInt(query.itemType) > 0)
                opt.itemType = parseInt(query.itemType);

            //类型
            if (query.category && query.category != 'all')opt.category = query.category;

            //范围
            if (query.range == 'around') {
                opt['$and'] = [{
                    $or: [{community: communityId},
                        {aroundCommunity: communityId},
                        {fromFlag: 'operate'}]
                }, {
                    $or: [{dealStatus: 0}, {
                        dealStatus: 1,
                        dealDate: {$gte: dealDate}
                    }]
                }]
            } else if (query.range == 'only') {
                opt.community = communityId;
                //opt['$or'] = [{dealStatus: 0}, {dealStatus: 1, dealDate: {$gte: dealDate}}]
                if (query.sort == 'smart')
                    query.sort = 'release';
            } else if (query.range == 'city' && user.community.communityType != 0) {
                opt['$or'] = [{city: cityId}, {fromFlag: 'operate'}];
                //opt['$or'] = [{dealStatus: 0}, {dealStatus: 1, dealDate: {$gte: dealDate}}]
            }

            //排序条件
            var sort = {};

            var index = Number(ts) * listPageSize;

            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170904   start   */
            if (!query.sort || query.sort == 'default') { // 发布时间
                sort.releaseDate = -1;
            }
            // else if (query.sort == 'release') {                              // 发布时间
            //     //if (ts != '0')opt.releaseDate = {$lt: new Date(Number(ts))};
            //     sort.releaseDate = -1;
            // }
            else if (query.sort == 'priceHighToLow') {                // 价格由高到低
                // if (ts != '0')opt.priceOrder = {$lt: Number(ts)};
                sort.presentPrice = -1; // 实际价格
                sort.priceOrder = -1;
            } else if (query.sort == 'priceLowToHigh') {                // 价格由低到高
                // if (ts != '0')opt.priceOrder = {$gt: Number(ts)};
                // sort.type = -1;
                // sort.releaseDate = -1;
                sort.presentPrice = 1; // 实际价格
                sort.priceOrder = 1;
            } else if (query.sort == 'location') {                      // 距离
                opt.locOrder = {$nearSphere: [lng.toFixed(4), lat]};
                //opt.location = {$geoWithin: {$centerSphere: [[lng, lat], 10]}};
                //sort.releaseDate = -1;
                //if (ts != '0') opt.location['$minDistance'] = Number(ts) / 6371;
            }
            console.log('query.sort:::' + query.sort);
            console.log('sort:::');
            console.log(sort);
            console.log('locOrder:::' + opt.locOrder);

            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170904   end   */

            var goodsFields = "itemType title desc presentPrice originalPrice priceOrder images location releaseDate type createdBy community dealStatus saleNumber fromFlag level";

            if (query.sort != 'smart') {
                var dataList = [];

                async.series([
                    function (callbackInner) {
                        if ((!query.range || query.range == "all") && query.sort == "city") { // 全国，城市排序。同城排0前面
                            opt.city = cityId;
                            //cityPopulateSort = {sort:{'name':1}};
                            Goods.count(opt, function (err, count) {
                                if (!err) {
                                    var diff = index - count;
                                    console.log("DIFF", diff);
                                    if (diff >= 0) {   // get goods from other cities, sorted by location
                                        index = diff;
                                        opt.city = {$ne: cityId};
                                        opt.locOrder = {$nearSphere: [lng.toFixed(4), lat]};
                                        callbackInner();
                                    } else {        // goods from same city
                                        if (-diff < listPageSize) {
                                            Goods.find(opt, goodsFields).populate('community', 'communityName')
                                                .skip(index).limit(listPageSize).sort({releaseDate:-1}).exec(function (err, result) {
                                                    if (!err && result != null) {
                                                        dataList = result;
                                                        opt.city = {$ne: cityId};
                                                        opt.locOrder = {$nearSphere: [lng.toFixed(4), lat]};
                                                    }
                                                    callbackInner();
                                                })
                                        } else {
                                            sort.releaseDate = -1;
                                            callbackInner();
                                        }
                                    }
                                } else {
                                    delete opt['city'];
                                    callbackInner();
                                }
                            })
                        } else {
                            callbackInner();
                        }
                    },
                    function(callbackInner){
                        console.log("CALLBACK INNER 2");
                        console.log(opt);
                        console.log("INDEX", index);
                        console.log("listPageSize", listPageSize);

                        Goods.find(opt, goodsFields).populate('community', 'communityName')
                            .skip(index).limit(listPageSize).sort(sort)
                            .exec(function (err, result) {
                                if (err) {
                                    callback(err, dataList);
                                    callbackInner();
                                } else {
                                    dataList = dataList.concat(result);
                                    async.eachSeries(dataList, function (goods, cb) {
                                        if (goods.location != null) {
                                            var distance = geolib.getDistance(
                                                {latitude: lat, longitude: lng},
                                                {latitude: goods.location.latitude, longitude: goods.location.longitude}
                                            );

                                            goods._doc.distance = distance > 1000 ? (distance / 1000).toFixed(1) + 'km' : distance + 'm';
                                            goods._doc.locationOrder = distance / 1000;
                                        }
                                        goods._doc.releaseDate = goods.releaseDate.getTime();
                                        if (goods.images.length > 0) {
                                            goods._doc.pic = imgHost + goods.images[0].imageURL + '?imageView2/1/w/200/h/200/q/85/format/jpg'
                                        }

                                        if (goods.community._id + '' == communityId) {
                                            var communityName = user.community.communityName;
                                            if (communityData && communityData._doc && communityData._doc.communityName) {
                                                communityName = communityData._doc.communityName;
                                            }
                                            goods._doc.userCommunity = communityName;
                                        }
                                        if (goods.fromFlag == 'operate') {
                                            goods._doc.userCommunity = goods.community.communityName;
                                        }

                                        var opt = ["goods:" + goods._id + ":detail", 'browner', 'replyCount'];

                                        redisClient.hmget(opt, function (err, result) {
                                            goods._doc.browner = result[0] == null ? 0 : result[0];
                                            goods._doc.replyCount = result[1] == null ? 0 : result[1];
                                            cb();
                                        });

                                    }, function (err) {
                                        var data = {
                                            list: dataList
                                        };

                                        //if (query.sort == 'release') {
                                        //    data.ts = result.length > 0 ? result[result.length - 1].releaseDate : Number(ts);
                                        //} else if (query.sort == 'priceHighToLow') {
                                        //    data.ts = result.length > 0 ? result[result.length - 1].priceOrder : Number(ts);
                                        //} else {
                                        //    data.ts = Number(ts) + 1;
                                        //}
                                        data.ts = Number(ts) + 1;
                                        console.log(data.ts);

                                        callback(null, data);
                                        callbackInner();
                                    });
                                }
                            })
                    }
                ], function(err){

                });
            } else {
                Community.findOne({_id: communityId}, 'price dateBuild', function (err, community) {
                    var fq = '&fq=isValid%3Atrue&fq=isInit%3A1&fq=city%3A' + cityId;

                    var price = '';
                    var date = '';
                    var priceA = '';
                    var dateA = '';
                    if (community.price != null) {
                        price = 'product(if(exists(communityPrice)%2Cscale(pow(sub(communityPrice%2C%24p)%2C2)%2C0%2C1)%2C1)%2C%24w2)';
                        priceA = '&p=' + community.price;
                    } else {
                        price = '%24w2'
                    }

                    if (community.dateBuild != null) {
                        date = 'product(if(exists(communityDateBuild)%2Cscale(pow(ms(communityDateBuild%2C%24bdate)%2C2)%2C0%2C1)%2C1)%2C%24w3)';
                        dateA = '&bdate=' + moment(community.dateBuild).format('YYYY-MM-DDTHH:mm:ss') + 'Z'
                    } else {
                        date = '%24w3';
                    }

                    if (query.category != 'all')fq += '&fq=category%3A' + query.category;
                    restClient.get('http://' + SolrHost + '/goods/select?q=%7B!func%7Dsum(' +
                        'product(scale(pow(geodist()%2C2)%2C0%2C1)%2C%24w1)%2C' +
                        price + '%2C' +
                        date + ')%0A' +
                        '&sort=score+asc%2CdateCreated+desc' +
                        fq + '&rows=20&start=' + ts +
                        '&wt=json&indent=true' +
                        '&sfield=point' +
                        '&pt=' + lat + ',' + lng
                        + priceA + dateA +
                        '&w1=0.4&w2=0.3&w3=0.3',
                        function (data, response) {
                            var res = [];
                            if (response.statusCode == 200) {
                                data = JSON.parse(data);
                                async.eachSeries(data.response.docs, function (item, cb) {
                                    Goods.findOne({_id: item._id}, goodsFields)
                                        .populate('community', 'communityName')
                                        .exec(function (err, goods) {
                                            if (goods != null) {
                                                if (goods.location != null) {
                                                    var distance = geolib.getDistance(
                                                        {latitude: lat, longitude: lng},
                                                        {latitude: goods.location.latitude, longitude: goods.location.longitude}
                                                    );

                                                    goods._doc.distance = distance > 1000 ? (distance / 1000).toFixed(1) + 'km' : distance + 'm';
                                                    goods._doc.locationOrder = distance / 1000;
                                                }
                                                goods._doc.releaseDate = goods.releaseDate.getTime();
                                                if (goods.images.length > 0) {
                                                    goods._doc.pic = imgHost + goods.images[0].imageURL + '?imageView2/1/w/256/h/200/q/85/format/jpg'
                                                }

                                                if (goods.community._id + '' == communityId) {
                                                    var communityName = user.community.communityName;
                                                    if (communityData && communityData._doc && communityData._doc.communityName) {
                                                        communityName = communityData._doc.communityName;
                                                    }
                                                    goods._doc.userCommunity = communityName;
                                                }

                                                if (goods.fromFlag == 'operate') {
                                                    goods._doc.userCommunity = goods.community.communityName;
                                                }
                                                res.push(goods)
                                            }
                                            var opt = ["goods:" + goods._id + ":detail", 'browner', 'replyCount'];

                                            redisClient.hmget(opt, function (err, result) {
                                                goods._doc.browner = result[0] == null ? 0 : result[0];
                                                goods._doc.replyCount = result[1] == null ? 0 : result[1];
                                                cb();
                                            });

                                        })
                                }, function () {
                                    callback(null, {list: res, ts: Number(ts) + listPageSize})
                                })
                            } else {
                                callback(null, {list: res, ts: 0})
                            }
                        });
                });
            }
    });
    });
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   end   */
};

exports.getGoodsItemRecord = function (userId, data, callback) {
    async.each(data.list, function (goods, cb) {
        if (goods.saleNumber != null) {
            GoodsSaleRecord.findOne({user: userId, goodsId: goods._id}, function (err, result) {
                goods._doc.isRecord = result != null;
                cb()
            })
        } else {
            goods._doc.isRecord = false;
            cb()
        }
    }, function (err) {
        callback(err, data)
    })
};


/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   start   */
exports.getGoodsDetail = function (user, query, goodsId, width, callback) {

    var currUserId = user._id;
    var currCommunityId = user.community._id;
    var currLocation = user.community.location;
    redisClient.get(currUserId + ":currCommunityId", function (errComm, replyComm) {
        if (!errComm) currCommunityId = replyComm;
        logger.debug("currCommunityId..." + currCommunityId);
        communityService.searchCommunityInfoByCommunityIdService(currCommunityId, function (err, data) {
            if (data && data._doc) {
                currLocation = data._doc.location;
            }

        var key = "goods:" + goodsId + ":detail";
            // var lat = query.lat ? Number(query.lat) : user.community.location.latitude; // 旧
            // var lng = query.lng ? Number(query.lng) : user.community.location.longitude; // 旧
            var lat = query.lat ? Number(query.lat) : currLocation .latitude; // 新
            var lng = query.lng ? Number(query.lng) : currLocation .longitude; // 新

        redisClient.hincrby(key, 'browner', 1);

        Goods.findOne({_id: goodsId}, 'itemType title isValid desc images presentPrice originalPrice dealStatus type community createdBy releaseDate location category saleNumber fromFlag')
            .populate('createdBy', 'nickName images huanxinUserName')
            .populate('community', 'communityName')
            .populate('category', '_id name')
            .exec(function (err, goods) {
                UserFollowups.count({goods: goodsId, user: user._id}, function (err, count) {
                    if (count > 0) {
                        goods._doc.isFollowUp = true;
                    } else {
                        goods._doc.isFollowUp = false;
                    }
                    async.eachSeries(goods.images, function (temp, callbackInner) {
                        if (temp.imageURL != null) {
                            temp._doc.bigImage = temp.imageURL;
                            temp.imageURL = imgHost + temp.imageURL + '?imageView2/1/h/400/w/400/q/85/format/jpg';
                        }
                        callbackInner();
                    }, function () {
                        var distance = geolib.getDistance(
                            {latitude: lat, longitude: lng},
                            {latitude: goods.location.latitude, longitude: goods.location.longitude}
                        );

                        if (goods.community.communityName != user.community.communityName && goods.fromFlag != 'operate') {
                            goods._doc.distance = distance > 1000 ? (distance / 1000).toFixed(1) + 'km' : distance + 'm';
                        }
                        if (goods._doc.createdBy.images[0].imageURL.indexOf("http://") < 0) {
                            goods._doc.createdBy.images[0].imageURL = imgHost + goods.createdBy.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                        }
                        goods._doc.releaseDate = goods.releaseDate.getTime();
                        var opt = [
                            key,
                            'browner',
                            'replyCount',
                            'collectionNum'
                        ];
                        redisClient.hmget(opt, function (err, result) {
                            goods._doc.browner = result[0] == null ? 0 : result[0];
                            goods._doc.replyCount = result[1] == null ? 0 : result[1];
                            goods._doc.collectionNum = result[2] == null ? 0 : result[2];
                            callback(err, goods)
                        });
                    });
                });
            });
        });
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   start   */
exports.getGoodsDetailForApp = function (user, query, goodsId, callback) {
    var currUserId = user._id;
    var currCommunityId = user.community._id;
    var currLocation = user.community.location;
    redisClient.get(currUserId + ":currCommunityId", function (errComm, replyComm) {
        if (!errComm) currCommunityId = replyComm;
        logger.debug("currCommunityId..." + currCommunityId);
        communityService.searchCommunityInfoByCommunityIdService(currCommunityId, function (err, data) {
            if (data && data._doc) {
                currLocation = data._doc.location;
            }

            var key = "goods:" + goodsId + ":detail";
        // var lat = query.lat ? Number(query.lat) : user.community.location.latitude; // 旧
        // var lng = query.lng ? Number(query.lng) : user.community.location.longitude; // 旧
            var lat = query.lat ? Number(query.lat) : currLocation.latitude; // 新
            var lng = query.lng ? Number(query.lng) : currLocation.longitude; // 新

        redisClient.hincrby(key, 'browner', 1);

        Goods.findOne({_id: goodsId}, 'itemType title desc images presentPrice originalPrice dealStatus type community createdBy releaseDate location category')
            .populate('createdBy', 'nickName images huanxinUserName')
            .populate('community', 'communityName')
            .populate('category', '_id name')
            .exec(function (err, goods) {
                UserFollowups.count({goods: goodsId, user: user._id}, function (err, count) {
                    if (count > 0) {
                        goods._doc.isFollowUp = true;
                    } else {
                        goods._doc.isFollowUp = false;
                    }
                    var distance = geolib.getDistance(
                        {latitude: lat, longitude: lng},
                        {latitude: goods.location.latitude, longitude: goods.location.longitude}
                    );

                    goods._doc.distance = distance > 1000 ? (distance / 1000).toFixed(1) + 'km' : distance + 'm';

                    var opt = [
                        key,
                        'browner',
                        'replyCount',
                        'collectionNum'
                    ];
                    redisClient.hmget(opt, function (err, result) {
                        goods._doc.browner = result[0] == null ? 0 : result[0];
                        goods._doc.replyCount = result[1] == null ? 0 : result[1];
                        goods._doc.collectionNum = result[2] == null ? 0 : result[2];
                        callback(err, goods)
                    });
                });
            });
        });
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   start   */
exports.addReply = function (user, input, callback) {
    var currUserId = user._id;
    var currCommunityId = user.community._id;
    redisClient.get(currUserId + ":currCommunityId", function (errComm, replyComm) {
        if (!errComm) currCommunityId = replyComm;
        logger.debug("currCommunityId..." + currCommunityId);

        var temp = new goodsReply();
        var key = "goods:" + input.goodsId + ":detail";

        input.replyDesc = input.replyDesc.replace('+', ' ').replace('%2b', "+");

        temp.replyDesc = decodeURIComponent(input.replyDesc);
        temp.goodsId = input.goodsId;
        // temp.community = user.community._id; // 旧
        temp.community = currCommunityId; // 新
        temp.repliedBy = user._id;
        temp.replyTo = input.replyTo;
        temp.quoteId = input.replyId;
        temp.save(function () {
            redisClient.hincrby(key, 'replyCount', 1);
            goodsReply.findOne({_id: temp._id})
                .populate('repliedBy', 'nickName images')
                .populate('community', 'communityName')
                .populate('replyTo', 'nickName')
                .populate('quoteId', 'replyDesc')
                .exec(function (err, result) {
                    if (result.repliedBy.images[0].imageURL.indexOf("http://") < 0) {
                        result._doc.headImg = imgHost + result.repliedBy.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                    } else {
                        result._doc.headImg = imgHost + result.repliedBy.images[0].imageURL;
                    }
                    result._doc.dateReplied = result.dateReplied.getTime();
                    //result._doc.replyTo = input.replyTo;
                    callback(err, result);
                });
                /*  宝宝树66小区二次改造    add   chenf  20170714   start   */
                taskService.finishTaskService(user._id, 'comment', function(err,result){
                    callback(err, result);
                });
                /*  宝宝树66小区二次改造    add   chenf  20170714   end   */
        });
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   end   */

exports.getMyGoods = function (user, ts, query, callback) {

    var index = Number(ts) * listPageSize;

    var field = [
        'browner',
        'collectionNum',
        'replyCount'
    ];

    var opt = {
        createdBy: user._id,
        isInit: 1,
        'images.0': {$exists: true},
        isValid: true
    };
    if (query && parseInt(query.itemType) > 0)
        opt.itemType = parseInt(query.itemType);

    Goods.find(opt, 'itemType title desc images presentPrice originalPrice dealStatus type community createdBy releaseDate location category releaseNum').skip(index).limit(listPageSize).sort('-dateCreated').populate('category', '_id name').exec(function (err, result) {
        async.eachSeries(result, function (temp, callbackInner) {
            var key = "goods:" + temp._id + ":detail";
            redisClient.HMGET(key, field, function (err, redisValue) {
                temp._doc.browner = redisValue[0] == null ? "0" : toolUtil.transformNumber(redisValue[0]);
                temp._doc.collectionNum = redisValue[1] == null ? "0" : toolUtil.transformNumber(redisValue[1]);
                temp._doc.replyCount = redisValue[2] == null ? "0" : toolUtil.transformNumber(redisValue[2]);
                temp._doc.detailUrl = "http://" + restHostIp + "/market/detail.html?goodsId=" + temp._id;

                var releaseDate = moment(new Date(temp.releaseDate)).format('YYYY-MM-DD');
                var now = moment().format('YYYY-MM-DD');
                if (releaseDate == now) {
                    temp._doc.isPublishNow = true;
                } else {
                    temp._doc.isPublishNow = false;
                }

                if (temp.dealStatus == 1) {
                    temp._doc.isPublishNow = true;
                }

                callbackInner();
            });
        }, function (err) {
            var data = {
                ts: Number(ts) + 1,
                list: result
            };
            callback(err, data);
        });
    });
};

exports.getRepliesByGoodsId = function (goodsId, ts, callback) {

    var index = Number(ts) * listPageSize;

    goodsReply.find({goodsId: goodsId}).sort('-dateReplied')
        .populate('repliedBy', 'nickName images')
        .populate('community', 'communityName')
        .populate('replyTo', 'nickName')
        .populate('quoteId', 'replyDesc')
        .skip(index).limit(listPageSize).exec(function (err, result) {
            async.eachSeries(result, function (temp, callbackInner) {
                if (temp.repliedBy.images[0].imageURL.indexOf("http://") < 0) {
                    temp._doc.headImg = imgHost + temp.repliedBy.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                } else {
                    temp._doc.headImg = temp.repliedBy.images[0].imageURL;
                }
                temp._doc.dateReplied = temp.dateReplied.getTime();
                callbackInner();
            }, function (err) {
                var data = {
                    ts: Number(ts) + 1,
                    list: result
                };
                callback(err, data);
            });
        });
};

exports.updateReleaseDate = function (goodsId, user, callback) {

    ActivityCommunity.findOne({
        type: 1,
        isValid: true,
        beginDate: {$lt: new Date()},
        endDate: {$gt: new Date()}
    }, function (err, activity) {
        if (activity != null) {
            ActivityPartake.findOne({user: user._id, activity: activity._id}, function (err, partake) {
                if (partake != null) {
                    exports.updateGoodsReleaseDate(goodsId, user, partake.saleNumber, callback);
                } else {
                    exports.updateGoodsReleaseDate(goodsId, user, null, callback);
                }
            })
        } else {
            exports.updateGoodsReleaseDate(goodsId, user, null, callback);
        }
    });


};


/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   start   */
exports.updateGoodsReleaseDate = function (goodsId, user, saleNumber, callback) {

    var currUserId = user._id;
    var currCommunityId = user.community._id;
    var currLocation = user.community.location;
    redisClient.get(currUserId + ":currCommunityId", function (errComm, replyComm) {
        if (!errComm) currCommunityId = replyComm;
        logger.debug("currCommunityId..." + currCommunityId);
        communityService.searchCommunityInfoByCommunityIdService(currCommunityId, function (err1, data1) {
            if (data1 && data1._doc) {
                /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170902   start   */
                // currLocation = data._doc.location; // 旧
                currLocation = data1._doc.location; // 新
                /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170902   end   */
            }
            var loc = {
            // longitude: user.community.location.longitude.toFixed(4) + '' + (4000000000 - Math.round(new Date().getTime() / 1000)), // 旧
            // latitude: user.community.location.latitude // 旧
                longitude: currLocation.longitude.toFixed(4) + '' + (4000000000 - Math.round(new Date().getTime() / 1000)), // 新
                latitude: currLocation.latitude // 新
            };

            var input = {
                releaseDate: new Date(),
                locOrder: loc,
                $inc: {releaseNum: 1}
            };

            if (saleNumber != null) input.saleNumber = saleNumber;

            Goods.update({_id: goodsId}, input, callback);

            Goods.findOne({_id: goodsId}, function (err, goods) {
                // redisClient.EXISTS('goods:smart:community:' + user.community._id, function (err, flag) { // 旧
                    redisClient.EXISTS('goods:smart:community:' + currCommunityId, function (err, flag) { // 新
                    if (flag == 1) {
                        // redisClient.ZREVRANK('sim_communities:' + user.community._id, user.community._id, function (err, i) { // 旧
                        //     redisClient.zadd('goods:smart:community:' + user.community._id, (i ? Number(i) : 0) + Number('0.' + new Date().getTime()), goodsId + ',' + goods.category); // 旧
                            redisClient.ZREVRANK('sim_communities:' + currCommunityId, currCommunityId, function (err, i) { // 新
                                redisClient.zadd('goods:smart:community:' + currCommunityId, (i ? Number(i) : 0) + Number('0.' + new Date().getTime()), goodsId + ',' + goods.category); // 新
                        });
                    }
                });
            })
        });
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   end   */

exports.queryDeal = function (goodsId, callback) {
    Goods.update({_id: goodsId}, {dealStatus: 1, dealDate: new Date()}, callback);

    Goods.findOne({_id: goodsId}, 'itemType saleNumber createdBy community title')
        .populate('createdBy', 'nickName')
        .populate('community', 'communityName')
        .exec(function (err, goods) {
            if (goods && goods.saleNumber != null) {
                var message = {
                    time: new Date().getTime(),
                    type: 1,
                    nickName: goods.createdBy.nickName,
                    community: goods.community.communityName,
                    msg: '刚刚成功交易了' + goods.title
                };

                redisClient.set('goods:sale:notify', JSON.stringify(message));

                var key = 'goods:sale:deal:number:' + moment().startOf('week').add(6, 'day').format('YYYYMMDD');
                redisClient.INCR(key, function (err, value) {
                    if (value != null && Number(value) % 5 == 0) {
                        var message = {
                            time: new Date().getTime(),
                            type: 2,
                            msg: '本期闪淘集市交易量已突破' + value + '单'
                        };
                        redisClient.set('goods:sale:notify', JSON.stringify(message));
                    }
                })

            }
        })
};

exports.delGoods = function (goodsId, callback) {
    Goods.findOne({_id: goodsId, isValid: true}, function (err, result) {
        if (result == null) {
            callback({message: '闲置已被删除'})
        } else {
            Goods.update({_id: goodsId}, {isValid: false}, function (err, re) {
                callback(err, result)
            });

            redisClient.ZREM('goods:smart:community:' + result.community, goodsId + ',' + result.category);
        }
    });
};

exports.delGoodsReply = function (replyId, callback) {
    goodsReply.remove({_id: replyId}, callback);
};

exports.getOtherGoods = function (user, ts, query, callback) {

    var index = Number(ts) * listPageSize;

    var communityId = query.communityId;

    var field = [
        'browner',
        'collectionNum',
        'replyCount'
    ];

    Users.findOne({_id: user}, 'community', function (err, other) {
        var opt = {
            createdBy: user,
            community: communityId ? communityId : other.community,
            isInit: 1,
            'images.0': {$exists: true},
            isValid: true
        };

        if (query && parseInt(query.itemType) > 0)
            opt.itemType = parseInt(query.itemType);

        Goods.find(opt, 'itemType title desc images presentPrice originalPrice dealStatus type community createdBy releaseDate location').skip(index).limit(listPageSize).sort('-dateCreated').exec(function (err, result) {
            async.eachSeries(result, function (temp, callbackInner) {
                var key = "goods:" + temp._id + ":detail";
                redisClient.HMGET(key, field, function (err, redisValue) {
                    temp._doc.browner = redisValue[0] == null ? "0" : toolUtil.transformNumber(redisValue[0]);
                    temp._doc.collectionNum = redisValue[1] == null ? "0" : toolUtil.transformNumber(redisValue[1]);
                    temp._doc.replyCount = redisValue[2] == null ? "0" : toolUtil.transformNumber(redisValue[2]);
                    temp._doc.detailUrl = "http://" + restHostIp + "/market/detail.html?goodsId=" + temp._id;

                    var releaseDate = moment(new Date(temp.releaseDate)).format('YYYY-MM-DD');
                    var now = moment().format('YYYY-MM-DD');
                    if (releaseDate == now) {
                        temp._doc.isPublishNow = true;
                    } else {
                        temp._doc.isPublishNow = false;
                    }

                    callbackInner();
                });
            }, function (err) {
                var data = {
                    ts: Number(ts) + 1,
                    list: result
                };
                callback(err, data);
            });
        });
    });
};

exports.updateGoodsService = function (goodsId, input, callback) {
    //input.releaseDate = new Date();

    Goods.findOne({_id: goodsId}, function (err, goods) {
        Goods.update({_id: goodsId}, input, callback);

        if (goods.category + '' != input.category) {

            redisClient.ZREM('goods:smart:community:' + goods.community, goodsId + ',' + goods.category);
            toolUtil.putMessageGoodsSmart({msgType: 2, goodsId: goodsId, category: goods.category});

            redisClient.EXISTS('goods:smart:community:' + goods.community, function (err, flag) {
                if (flag == 1) {
                    redisClient.ZREVRANK('sim_communities:' + goods.community, goods.community, function (err, i) {
                        redisClient.zadd('goods:smart:community:' + goods.community, (i ? Number(i) : 0) + Number('0.' + goods.releaseDate.getTime()), goods._id + ',' + input.category);
                    });
                }

                toolUtil.putMessageGoodsSmart({msgType: 1, goodsId: goods._id})
            });
        }
    })
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   start   */
exports.getRecGoodsListService = function (user, ts, query, callback) {

    var currUserId = user._id;
    var currCommunityId = user.community._id;
    var currLocation = user.community.location;
    redisClient.get(currUserId + ":currCommunityId", function (errComm, replyComm) {
        if (!errComm) currCommunityId = replyComm;
        logger.debug("currCommunityId..." + currCommunityId);
        communityService.searchCommunityInfoByCommunityIdService(currCommunityId, function (err, communityData) {
            if (communityData && communityData._doc) {
                currLocation = communityData._doc.location;
            }
            // var lat = query.lat ? Number(query.lat) : user.community.location.latitude; // 旧
            // var lng = query.lng ? Number(query.lng) : user.community.location.longitude; // 旧
            var lat = query.lat ? Number(query.lat) : currLocation.latitude; // 新
            var lng = query.lng ? Number(query.lng) : currLocation.longitude; // 新
            var index = Number(ts) * listPageSize;

            var opt = {
                isValid: true,
                isInit: 1,
                level: 1,
                'images.0': {$exists: true}
            };

            if (query && parseInt(query.itemType) > 0)
                opt.itemType = parseInt(query.itemType);

            Goods.find(opt, 'itemType title presentPrice originalPrice priceOrder images location releaseDate type createdBy community dealStatus fromFlag')
                .populate('community', 'communityName')
                .skip(index).limit(listPageSize).sort({recDate: -1})
                .exec(function (err, result) {
                    if (err) {
                        callback(err, null)
                    } else {
                        result.forEach(function (goods) {
                            if (goods.location != null) {
                                var distance = geolib.getDistance(
                                    {latitude: lat, longitude: lng},
                                    {latitude: goods.location.latitude, longitude: goods.location.longitude}
                                );

                                goods._doc.distance = distance > 1000 ? (distance / 1000).toFixed(1) + 'km' : distance + 'm';
                                goods._doc.locationOrder = distance / 1000;
                            }
                            goods._doc.releaseDate = goods.releaseDate.getTime();
                            if (goods.images.length > 0) {
                                goods._doc.pic = imgHost + goods.images[0].imageURL + '?imageView2/1/w/256/h/200/q/85/format/jpg'
                            }

                            // if (goods.community._id + '' == user.community._id) { // 旧
                            if (goods.community._id + '' == currCommunityId) { // 新
                                var communityName = user.community.communityName;
                                if (communityData && communityData._doc && communityData._doc.communityName) {
                                    communityName = communityData._doc.communityName;
                                }
                                goods._doc.userCommunity = communityName;
                            }

                            if (goods.fromFlag == 'operate') {
                                goods._doc.userCommunity = goods.community.communityName;
                            }

                        });

                        var data = {
                            list: result,
                            ts: Number(ts) + 1
                        };
                        callback(null, data);
                    }
                })
            });
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   end   */


/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   start   */
exports.getSaleGoodsListService = function (user, ts, query, callback) {
    var currUserId = user._id;
    var currCommunityId = user.community._id;
    var currLocation = user.community.location;
    redisClient.get(currUserId + ":currCommunityId", function (errComm, replyComm) {
        if (!errComm) currCommunityId = replyComm;
        logger.debug("currCommunityId..." + currCommunityId);

        communityService.searchCommunityInfoByCommunityIdService(currCommunityId, function (err, communityData) {
            if (communityData && communityData._doc) {
                currLocation = communityData._doc.location;
            }

            // var lat = query.lat ? Number(query.lat) : user.community.location.latitude; // 旧
            // var lng = query.lng ? Number(query.lng) : user.community.location.longitude; // 旧
            var lat = query.lat ? Number(query.lat) : currLocation.latitude; // 新
            var lng = query.lng ? Number(query.lng) : currLocation.longitude; // 新
            var index = Number(ts) * listPageSize;

            var opt = {
                isValid: true,
                isInit: 1,
                saleNumber: {$ne: null},
                'images.0': {$exists: true}
            };
            if (query && parseInt(query.itemType) > 0)
                opt.itemType = parseInt(query.itemType);

            Goods.find(opt, 'itemType title presentPrice originalPrice priceOrder images location releaseDate type createdBy community dealStatus saleNumber fromFlag')
                .populate('community', 'communityName')
                .sort({saleNumber: 1, dateCreated: -1}).skip(index).limit(listPageSize)
                .exec(function (err, result) {
                    if (err) {
                        callback(err, null)
                    } else {
                        result.forEach(function (goods) {
                            if (goods.location != null) {
                                var distance = geolib.getDistance(
                                    {latitude: lat, longitude: lng},
                                    {latitude: goods.location.latitude, longitude: goods.location.longitude}
                                );

                                goods._doc.distance = distance > 1000 ? (distance / 1000).toFixed(1) + 'km' : distance + 'm';
                                goods._doc.locationOrder = distance / 1000;
                            }
                            goods._doc.releaseDate = goods.releaseDate.getTime();
                            if (goods.images.length > 0) {
                                goods._doc.pic = imgHost + goods.images[0].imageURL + '?imageView2/1/w/256/h/200/q/85/format/jpg'
                            }

                            // if (goods.community._id + '' == user.community._id) { // 旧
                            if (goods.community._id + '' == currCommunityId) { // 新
                                var communityName = user.community.communityName;
                                if (communityData && communityData._doc && communityData._doc.communityName) {
                                    communityName = communityData._doc.communityName;
                                }
                                goods._doc.userCommunity = communityName;
                            }

                            if (goods.fromFlag == 'operate') {
                                goods._doc.userCommunity = goods.community.communityName;
                            }

                        });

                        var data = {
                            list: result,
                            ts: Number(ts) + 1
                        };
                        callback(null, data);
                    }
                })
        });
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   end   */


/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   start   */
exports.initSmartGoodsListService = function (token) {
    toolUtil.getUserByToken(token, function (err3, user) {
        if (err3) {
            logger.error('Failed to initSmartGoodsListService -- ' + err.message)
        } else {

            var currUserId = user._id; // 用户ID
            var communityId = ''; // 小区ID
            var cityId = ''; // 城市ID

            async.parallel([
                function(callbackInner) {
                    redisClient.get(currUserId + ":currCommunityId", function (errComm, replyComm) {
                        if (!errComm) communityId = replyComm;
                        callbackInner(null, replyComm);
                    });
                },
                function(callbackInner) {
                    redisClient.get(currUserId + ":currCityId", function (errCity, replyCity) {
                        if (!errCity) cityId = replyCity;
                        callbackInner(null, replyCity);
                    });
                }
            ], function(err1, result1) {
                communityId = result1[0];
                cityId = result1[1];
                if (communityId == null || communityId == '') {
                    communityId = user.community._id;
                }
                if (cityId == null || cityId == '') {
                    cityId = user.community.cityId;
                }

                // redisClient.EXISTS('goods:smart:community:' + user.community._id, function (err, flag) { // 旧
                    redisClient.EXISTS('goods:smart:community:' + communityId, function (err2, flag2) { // 新
                    logger.debug("initSmartGoodsListService flag..." + communityId + "@" + flag2);
                    if (flag2 == 0) {
                        var date = moment().add(-10, 'day').toDate();

                        var sOpt = {
                            dateCreated: {$gt: date},
                            isValid: true,
                            isInit: 1,
                            'images.0': {$exists: true},
                            // city: user.community.cityId // 旧
                            city: cityId // 新
                        };


                        Goods.find(sOpt, 'itemType title presentPrice originalPrice priceOrder images location releaseDate type createdBy community dealStatus category saleNumber')
                            .exec(function (err, result) {
                                // var args = ['sim_communities:' + user.community._id, 0, -1]; // 旧
                                var args = ['sim_communities:' + communityId, 0, -1]; // 新
                                redisClient.ZREVRANGE(args, function (err, comms) {

                                    result.forEach(function (goods) {

                                        goods._doc.releaseDate = goods.releaseDate.getTime();
                                        goods._doc.similarOrder = (comms.indexOf(goods.community + '') == -1 ? 0 : comms.indexOf(goods.community + '')) + Number('0.' + goods._doc.releaseDate);

                                        // redisClient.zadd('goods:smart:community:' + user.community._id, goods._doc.similarOrder, goods._id + ',' + goods.category); // 旧
                                        redisClient.zadd('goods:smart:community:' + communityId, goods._doc.similarOrder, goods._id + ',' + goods.category); // 新
                                    });

                                    // redisClient.EXPIRE('goods:smart:community:' + user.community._id, 259200); // 旧
                                    redisClient.EXPIRE('goods:smart:community:' + communityId, 259200); // 新

                                });
                            })
                    }
                });
            });
        }
    })
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   end   */

exports.getSaleNotifyMessageService = function (callback) {
    redisClient.get('goods:sale:notify', callback);
};

exports.addSaleRecordService = function (user, input, callback) {
    var temp = new GoodsSaleRecord();
    temp.user = user._id;
    temp.nickName = user.nickName;
    temp.mobilePhone = user.mobilePhone;
    temp.goodsId = input.goodsId;
    temp.goodsTitle = input.goodsTitle;

    temp.save(callback);
};

exports.sendMessageService = function (user, input, callback) {
    var key = 'sale:message:' + user.huanxinUserName + ':' + input.goodsId;

    redisClient.get(key, function (err, value) {
        if (value == null) {
            toolUtil.getAndCacheHuanXinToken(function (err, token) {
                var args = {
                    data: {
                        "target_type": "users",
                        "target": [input.huanxinUserName],
                        "msg": {
                            "type": "txt",
                            "msg": input.message
                        },
                        "from": user.huanxinUserName,
                        "ext": {
                            "nickName": user.nickName,
                            "avatar": user.images[0].imageURL,
                            "objId": user._id
                        }
                    },
                    headers: {
                        "Content-Type": "application/json",
                        "Authorization": "Bearer " + token
                    }
                };
                restClient.post("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/messages", args, function (data, response) {
                    logger.info(data);
                    redisClient.set(key, 'yes');
                    redisClient.EXPIRE(key, 43200);
                }).on('error', function (err) {
                    logger.error('sendMessageByCustomService' + err.message);
                });
            });
        }

        callback();
    });
};


/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   start   */
exports.searchGoodsService = function (user, keyword, goodsClaId, ts, callback) {

    var currUserId = user._id;
    var currCommunityId = user.community._id;
    var currLocation = user.community.location;
    redisClient.get(currUserId + ":currCommunityId", function (errComm, replyComm) {
        if (!errComm) currCommunityId = replyComm;
        logger.debug("currCommunityId..." + currCommunityId);

        communityService.searchCommunityInfoByCommunityIdService(currCommunityId, function (err, communityData) {
            if (communityData && communityData._doc) {
                currLocation = communityData._doc.location;
            }
            // var lat = user.community.location.latitude; // 旧
            // var lng = user.community.location.longitude; // 旧
            var lat = currLocation.latitude; // 新
            var lng = currLocation.longitude; // 新

            var query = solrGoodsClient.createQuery();
            /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 start */
            if (goodsClaId == "" && keyword != "") {
                query.q({"descTitle": keyword}).fl(['_id', 'dateCreated', 'title'])
                    .matchFilter('isValid', true).matchFilter('isInit', 1).matchFilter('city', user.community.cityId).rows(20)
                    .sort({dateCreated: 'desc', _id: 'desc'}).cursorMark(ts);
            } else if (goodsClaId != "" && keyword == "") {
                query.q({"category": goodsClaId}).fl(['_id', 'dateCreated', 'title'])
                    .matchFilter('isValid', true).matchFilter('isInit', 1).matchFilter('city', user.community.cityId).rows(20)
                    .sort({dateCreated: 'desc', _id: 'desc'}).cursorMark(ts);
            } else {
                query.q({"descTitle": keyword}).fl(['_id', 'dateCreated', 'title'])
                    .matchFilter('isValid', true).matchFilter('isInit', 1).matchFilter('city', user.community.cityId)
                    .matchFilter('category', goodsClaId).rows(20)
                    .sort({dateCreated: 'desc', _id: 'desc'}).cursorMark(ts);
            }
            /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 end */

            solrGoodsClient.search(query, function (err1, solrResult) {
                if (err1) {
                    callback(err1, null)
                } else {
                    var ids = [];

                    solrResult.response.docs.forEach(function (item) {
                        ids.push(item._id)
                    });

                    Goods.find({
                        _id: {$in: ids}
                    }, 'itemType title presentPrice originalPrice priceOrder images location releaseDate type createdBy community dealStatus saleNumber fromFlag')
                        .populate('community', 'communityName')
                        .sort({dateCreated: -1}).exec(function (err2, result) {
                            result.forEach(function (goods) {
                                if (goods.location != null) {
                                    var distance = geolib.getDistance(
                                        {latitude: lat, longitude: lng},
                                        {latitude: goods.location.latitude, longitude: goods.location.longitude}
                                    );

                                    goods._doc.distance = distance > 1000 ? (distance / 1000).toFixed(1) + 'km' : distance + 'm';
                                    goods._doc.locationOrder = distance / 1000;
                                }
                                goods._doc.releaseDate = goods.releaseDate.getTime();
                                if (goods.images.length > 0) {
                                    goods._doc.pic = imgHost + goods.images[0].imageURL + '?imageView2/1/w/256/h/200/q/85/format/jpg'
                                }

                                // if (goods.community._id + '' == user.community._id) { // 旧
                                    if (goods.community._id + '' == currCommunityId) { // 新
                                        var communityName = user.community.communityName;
                                        if (communityData && communityData._doc && communityData._doc.communityName) {
                                            communityName = communityData._doc.communityName;
                                        }
                                        goods._doc.userCommunity = communityName;
                                }

                                if (goods.fromFlag == 'operate') {
                                    goods._doc.userCommunity = goods.community.communityName;
                                }

                            });

                            var data = {
                                list: result,
                                ts: solrResult.nextCursorMark
                            };
                            callback(null, data);
                        })
                }
            })
        });
    });

};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170818   end   */

exports.publicGetMarketBannersService = function (callback) {
    Banner.find({
        beginDate: {$lte: new Date()},
        endDate: {$gte: new Date()},
        type: 2,
        isValid: true
    }, 'url imageURL name bannerOrder').sort({bannerOrder: -1}).exec(function (err, result) {
        if (err) {
            callback(err)
        } else {
            result.forEach(function (temp) {
                temp.imageURL = imgHost + temp.imageURL + '?imageView2/1/h/276/w/750/q/75/format/jpg'
            });
            callback(null, result)
        }
    })
};

exports.publicGetGoodsListService = function (ts, query, callback) {
    var index = Number(ts) * listPageSize;

    var opt = {
        isValid: true,
        isInit: 1,
        'images.0': {$exists: true}
    };

    if (query && parseInt(query.itemType) > 0)
        opt.itemType = parseInt(query.itemType);

    Goods.find(opt, 'itemType title desc presentPrice originalPrice priceOrder images location releaseDate type createdBy community dealStatus saleNumber fromFlag level')
        .populate('community', 'communityName')
        .skip(index).limit(listPageSize).sort({_id: -1})
        .exec(function (err, result) {
            if (err) {
                callback(err, null)
            } else {
                async.eachSeries(result, function (goods, cb) {
                    goods._doc.releaseDate = goods.releaseDate.getTime();
                    if (goods.images.length > 0) {
                        goods._doc.pic = imgHost + goods.images[0].imageURL + '?imageView2/1/w/200/h/200/q/85/format/jpg'
                    }
                    var opt = ["goods:" + goods._id + ":detail", 'browner', 'replyCount'];
                    redisClient.hmget(opt, function (err, result) {
                        goods._doc.browner = result[0] == null ? 0 : result[0];
                        goods._doc.replyCount = result[1] == null ? 0 : result[1];
                        cb();
                    });
                }, function (err) {
                    var data = {
                        list: result,
                        ts: Number(ts) + 1
                    };
                    callback(null, data);
                });
            }
        })
};

/* 宝宝树66小区 sprint5 66小区APP"我的"页面 新增我的拼团收藏功能 add wangcan 20171117 start */
// APP调用-我的拼团收藏
exports.getFightGroupsCollectListService = function (ts, token, screenWidth, screenHeight, query, callback) {
    try {
        logger.debug("token后台解码009999901。。。。" + token + "客户端屏幕宽高。。。" + screenWidth + "..." + screenHeight);
        token = toolUtil.encodeAtoB(token);
        logger.debug("token后台解码009999902。。。。" + token);
        var requestUrl = mtFgCollectUrl;
        var pageno = Number(ts) + 1;
        var timestamp = Date.parse(new Date());
        // var reqData = {
        //     'token' : token,
        //     'source' : '2',
        //     'collecttype' : '1',
        //     'curpage' : pageno.toString(),
        //     'pageSize' : '20'
        // };

        var clientInfo = {
            'clientAppVersion' : '',
            'clientYunyuVersion' : '',
            'clientSystem':'',
            'clientVersion':'',
            'deviceCode':'',
            'latitude':'',
            'longitude':'',
            'traderName':'',
            'partner':'',
            'nettype':'',
            'clientip':'',
            'screenwidth':screenWidth,
            'screenheight':screenHeight
        };
        var tempParam = "source=2&collecttype=1&pageSize=20&curpage="+pageno.toString();
        var args = {
            data: tempParam,
            headers: {
                'clientInfo': JSON.stringify(clientInfo),
                'token' : token,
                'timestamp' : timestamp,
                'signature' : '350F163035D51E8D400114BE70EDFBFA',
                'platform' : '1',
                'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8'
                // 'Accept-encoding' : 'gzip, deflate'
            }
        };
        logger.info(requestUrl);
        logger.info(args);

        restClient.post(requestUrl, args, function (tempData, response) {
            logger.info('取得美囤拼团收藏返回状态值:' + response.statusCode);
            // logger.info('美囤拼团收藏接口返回值：。。。' + tempData);
            if (response.statusCode == 200 && tempData != null && tempData != 'unknown') {
                var returnData = JSON.parse(tempData);
                if (returnData.rtn_code == '0') {
                    logger.info("rtn_msg:..." + returnData.rtn_msg);
                    logger.info("rtn_code:..." + returnData.rtn_code);
                    logger.info("返回的当前页的数据条数:..." + returnData.data.list.length);
                    returnData.ts = pageno;
                    callback(null, returnData);
                } else {
                    logger.debug('rtn_code!=0');
                    logger.debug(returnData.rtn_msg);
                    logger.debug(returnData);
                    callback(null, returnData);
                }
            } else {
                logger.debug(tempData);
                callback(null, null);
            }
        }).on('error', function (err) {
            logger.error(err);
           callback(err, null);
        });
    } catch (e) {
        logger.error(e);
        callback(e, null);
    }
};
/* 宝宝树66小区 sprint5 66小区APP"我的"页面 新增我的拼团收藏功能 add wangcan 20171117 end */

exports.publicGetGoodsDetailService = function (query, goodsId, width, callback) {
    var key = "goods:" + goodsId + ":detail";
    redisClient.hincrby(key, 'browner', 1);

    Goods.findOne({_id: goodsId}, 'itemType title isValid desc images presentPrice originalPrice dealStatus type community createdBy releaseDate location category saleNumber fromFlag')
        .populate('createdBy', 'nickName images huanxinUserName')
        .populate('community', 'communityName')
        .populate('category', '_id name')
        .exec(function (err, goods) {
            goods._doc.isFollowUp = false;

            async.eachSeries(goods.images, function (temp, callbackInner) {
                if (temp.imageURL != null) {
                    temp._doc.bigImage = temp.imageURL;
                    temp.imageURL = imgHost + temp.imageURL + '?imageView2/1/h/400/w/400/q/85/format/jpg';
                }
                callbackInner();
            }, function () {
                if (goods._doc.createdBy.images[0].imageURL.indexOf("http://") < 0) {
                    goods._doc.createdBy.images[0].imageURL = imgHost + goods.createdBy.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                }
                goods._doc.releaseDate = goods.releaseDate.getTime();
                var opt = [
                    key,
                    'browner',
                    'replyCount',
                    'collectionNum'
                ];
                redisClient.hmget(opt, function (err, result) {
                    goods._doc.browner = result[0] == null ? 0 : result[0];
                    goods._doc.replyCount = result[1] == null ? 0 : result[1];
                    goods._doc.collectionNum = result[2] == null ? 0 : result[2];
                    callback(err, goods)
                });
            });
        });
};